package com.ruan.quartz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruan.mapper.*;
import com.ruan.pojo.*;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.*;

public class MonthCountQuartz extends QuartzJobBean {

    @Resource
    private MonthCountMapper monthCountMapper;

    @Resource
    private OverTimeMapper overTimeMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private OnDutyMapper onDutyMapper;

    @Resource
    private BusinessTripMapper businessTripMapper;

    //月统计定时任务
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        try {
            Date lastDay = new Date(System.currentTimeMillis());
            String[] strings = lastDay.toString().split("-");
//            Integer maxDayOfMonth = Integer.parseInt(strings[2]);//每月最大天数

            System.out.println("(当前时间)lastDay是："+lastDay);//2024-04-30
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(lastDay);//2024-04
            String format2 = sdf.format(lastDay) + "-01";//2024-04-01
            Date firstDay = new Date(sdf2.parse(format2).getTime());
            System.out.println("(该月的第一天)firstDay是："+firstDay);//2024-04-01

            LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.ne(Employee::getStatus,"离职");
            queryWrapper.ne(Employee::getStatus,"待审核");
            List<Employee> employeeList = employeeMapper.selectList(queryWrapper);

            List<String> phoneList = new ArrayList<>();
            for (Employee employee : employeeList) {
                phoneList.add(employee.getPhone());
            }

            for (String phone : phoneList) {
                MonthCount monthCount = new MonthCount();
                monthCount.setMonth(format);//设置月份 2024-04

                LambdaQueryWrapper<BusinessTrip> tripWrapper = new LambdaQueryWrapper<>();
                LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Employee::getPhone,phone);
                Employee employee = employeeMapper.selectOne(queryWrapper1);

                tripWrapper.eq(BusinessTrip::getEmployeeId,employee.getId());
                tripWrapper.between(BusinessTrip::getLeaveTime,firstDay,lastDay).or()
                .between(BusinessTrip::getBackTime,firstDay,lastDay);
                Integer tripCount = businessTripMapper.selectCount(tripWrapper);
                monthCount.setTripCount(tripCount);//设置出差次数

                QueryWrapper<OnDuty> onDutyWrapper = new QueryWrapper<>();

                onDutyWrapper.eq("employee_id",employee.getId());
//                onDutyWrapper.eq("phone",phone);
                onDutyWrapper.between("day",firstDay,lastDay);
                onDutyWrapper.groupBy("status");
                onDutyWrapper.select("status","count(*) as count");
                List<Map<String, Object>> maps = onDutyMapper.selectMaps(onDutyWrapper);

                QueryWrapper<OnDuty> onDutyWrapper2 = new QueryWrapper<>();


                onDutyWrapper2.eq("employee_id",employee.getId());
//                onDutyWrapper2.eq("phone",phone);
                onDutyWrapper2.between("day",firstDay,lastDay);
                Integer onDutySumDay = onDutyMapper.selectCount(onDutyWrapper2);//出勤总天数
                System.out.println("出勤总天数是："+onDutySumDay);
                Map<String,Integer> statusCountMaps = new HashMap<>();
                for (Map<String, Object> map : maps) {
                    Collection<Object> values = map.values();
                    Object[] array = values.toArray();
                    String status = array[1].toString();
                    int count = Integer.parseInt(array[0].toString());
                    statusCountMaps.put(status,count);
                }

                Integer lateCount = statusCountMaps.get("迟到");
                Integer restCount = statusCountMaps.get("休息");
                restCount = restCount != null ? restCount : 0;//默认值设为0，防止空指针
                Integer earlyCount = statusCountMaps.get("早退");
                Integer leaveCount = statusCountMaps.get("请假");
                Integer awayWorkDay = statusCountMaps.get("旷工");

                if (lateCount != null){
                    monthCount.setLateCount(lateCount);//设置迟到天数
                }else {
                    monthCount.setLateCount(0);//设置迟到天数
                }

                if (earlyCount != null){
                    monthCount.setEarlyCount(earlyCount);//设置早退天数
                }else {
                    monthCount.setEarlyCount(0);//设置早退天数
                }

                if (leaveCount != null){
                    monthCount.setLeaveDay(leaveCount);//设置请假天数
                }else {
                    monthCount.setLeaveDay(0);//设置请假天数
                }

                if (awayWorkDay != null){
                    monthCount.setAwayWorkDay(awayWorkDay);//设置旷工天数
                }else {
                    monthCount.setAwayWorkDay(0);//设置旷工天数
                }
                System.out.println("哪个是空的:"+monthCount+'\n'+onDutySumDay+'\n'+monthCount.getLeaveDay()+'\n'+restCount);
                if (monthCount != null && onDutySumDay != null && monthCount.getLeaveDay() != null && restCount != null) {
                    //为了避免空指针异常，可以在计算实际出勤天数之前，确保monthCount对象不为null，并且设置onDutyCount属性。
                    int onDutyCount = onDutySumDay - monthCount.getLeaveDay() - restCount;
                    monthCount.setOnDutyCount(onDutyCount);//设置实际出勤天数
                    System.out.println("实际出勤天数:"+monthCount.getOnDutyCount());
                } else {
                    // 处理对象为null的情况
                    System.out.println("某些对象是空的。。");
                }

                //出现空指针异常可能是因为monthCount、onDutySumDay、leaveDay、restCount中的某个对象为null
//                monthCount.setOnDutyCount(onDutySumDay-monthCount.getLeaveDay()-restCount);//设置实际出勤天数

                LambdaQueryWrapper<OverTime> overTimeWrapper = new LambdaQueryWrapper<>();
                //----------------------------------------
                LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(Employee::getPhone,phone);
                Employee employee1 = employeeMapper.selectOne(queryWrapper2);

                overTimeWrapper.eq(OverTime::getEmployeeId,employee1.getId());

//                overTimeWrapper.eq(OverTime::getPhone,phone);
                overTimeWrapper.between(OverTime::getOverTimeDate,firstDay,lastDay);
                List<OverTime> overTimes = overTimeMapper.selectList(overTimeWrapper);
                if (overTimes!=null){
                    Integer hours = 0;
                    for (OverTime overTime : overTimes) {
                        hours = hours +overTime.getHours();
                    }
                    monthCount.setOverTimeHours(hours);//设置加班时长
                }else {
                    monthCount.setOverTimeHours(0);//设置加班时长
                }
                monthCount.setEmployeeId(employee1.getId());
                monthCount.setDepartmentId(employee1.getDepartmentId());
                monthCountMapper.insert(monthCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
